<!-- 服务商选择器-多选 -->
<template>
  <el-select
    v-model="currentItems"
    v-loadMore="selectLoadMore"
    multiple
    filterable
    remote
    :placeholder="`请选择服务商`"
    clearable
    @change="handleChange"
    :remote-method="remoteMethod"
    :loading="loading"
    :disabled="disabled"
    style="width:100%"
    value-key="id"
  >
    <el-option
      v-for="item in options"
      :key="item.id"
      :label="item.cname"
      :value="item"
    ></el-option>
  </el-select>
</template>

<script>
import { getCooperateList } from "@/api/facilitator";
import { arrayUnique } from '@/utils/ruoyi'

export default {
  props: {
    defaultValue: {
      type: Number | String
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    defaultValue: {
      handler(nval) {
        const currentIDS = this.currentItems && this.currentItems.length ? this.currentItems.map(v=> v.id) : [];
        const newIDS = nval && nval.length ? nval.map(v=> v.id) : [];
        if(JSON.stringify(newIDS) !== JSON.stringify(currentIDS)){
          this.currentItems = nval;
        }
      },
      immediate: true,
      deep: true
    }
  },
  data() {
    return {
      currentItems: [],
      options: [],
      getParams: {
        pageNum: 1,
        pageSize: 10,
        searchValue: undefined
      },
      total: 0,
      loading: false
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询所属事业部下的服务商下拉树结构 */
    async getList() {
      const { rows, total } = await getCooperateList(this.getParams);
      this.total = total;
      if(this.getParams.pageNum === 1){ this.options = [] };
      const lists = rows.map(v=> {
        return {
          id: v.companyId,
          cname: v.companyName
        }
      });
      this.options = arrayUnique([...this.options, ...lists], 'id');
      console.log(JSON.parse(JSON.stringify(this.options)));
    },
    // 下拉加载更多
    selectLoadMore() {
      if(this.options.length < this.total){
        this.getParams.pageNum++;
        this.getList();
      }
    },
    async remoteMethod(query){
      this.loading = true;
      this.getParams.pageNum = 1;
      this.getParams.pageSize = 10;
      this.getParams.searchValue = query;
      await this.getList();
      this.loading = false;
    },
    handleChange(e){
      this.$emit('update:defaultValue', e);
      this.$emit('change', e);
    }
  },
};
</script>

<style lang="scss" scoped></style>
